package com.atguigu.tingshu.album.service.impl;

import com.atguigu.tingshu.album.config.VodConstantProperties;
import com.atguigu.tingshu.album.mapper.AlbumInfoMapper;
import com.atguigu.tingshu.album.mapper.TrackInfoMapper;
import com.atguigu.tingshu.album.mapper.TrackStatMapper;
import com.atguigu.tingshu.album.service.TrackInfoService;
import com.atguigu.tingshu.album.service.VodService;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.util.UploadFileUtil;
import com.atguigu.tingshu.model.album.AlbumInfo;
import com.atguigu.tingshu.model.album.TrackInfo;
import com.atguigu.tingshu.model.album.TrackStat;
import com.atguigu.tingshu.query.album.TrackInfoQuery;
import com.atguigu.tingshu.vo.album.TrackInfoVo;
import com.atguigu.tingshu.vo.album.TrackListVo;
import com.atguigu.tingshu.vo.album.TrackMediaInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qcloud.vod.VodUploadClient;
import com.qcloud.vod.model.VodUploadRequest;
import com.qcloud.vod.model.VodUploadResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Slf4j
@Service
@SuppressWarnings({"all"})
public class TrackInfoServiceImpl extends ServiceImpl<TrackInfoMapper, TrackInfo> implements TrackInfoService {

    @Autowired
    private TrackInfoMapper trackInfoMapper;

    @Autowired
    private VodConstantProperties vodConstantProperties;

    @Autowired
    private AlbumInfoMapper albumInfoMapper;

    @Autowired
    private VodService vodService;

    @Autowired
    private TrackStatMapper trackStatMapper;

    @Override
    public void updateTrackInfo(TrackInfoVo trackInfoVo, Long trackId) {
        //区分是否修改了当前的数据文件
        //根据id获取到声音对象
        TrackInfo trackInfo = this.getById(trackId);
        //获取旧的媒体文件id
        String oldMediaFileId = trackInfo.getMediaFileId();
        //拷贝数据
        BeanUtils.copyProperties(trackInfoVo, trackInfo);
        //最新文件id
        if(!trackInfoVo.getMediaFileId().equals(oldMediaFileId)){
            //  说明当前音频文件被修改了！ 重新计算当前声音的大小，类型，url，时长;
            TrackMediaInfoVo mediaInfo = vodService.getMediaInfo(trackInfoVo.getMediaFileId());
            //赋值最新数据
            trackInfo.setMediaUrl(mediaInfo.getMediaUrl());
            trackInfo.setMediaDuration(mediaInfo.getDuration());
            trackInfo.setMediaType(mediaInfo.getType());
            trackInfo.setMediaSize(mediaInfo.getSize());
            //删除云点播中的数据
            vodService.deleteMedia(oldMediaFileId);
        }
        //更新数据
        this.updateById(trackInfo);

    }

    @Override
    public TrackInfo getTrackInfo(Long trackId) {
        //创建trackinfo对象
        TrackInfo trackInfo = trackInfoMapper.selectById(trackId);
        //返回数据
        return trackInfo;
    }

    @Override
    public void removeTrackInfoById(Long trackId) {
        //先获取和专辑对象
        TrackInfo trackInfo = this.getById(trackId);
        //删除track_info中的信息
        trackInfoMapper.deleteById(trackId);
        //删除track_stat中的信息
        this.trackStatMapper.delete(new LambdaQueryWrapper<TrackStat>().eq(TrackStat::getTrackId, trackId));
        //修改专辑中声音数量
        AlbumInfo albumInfo = albumInfoMapper.selectById(trackInfo.getAlbumId());
        albumInfo.setIncludeTrackCount(albumInfo.getIncludeTrackCount() - 1);
        //更新专辑声音数量
        this.albumInfoMapper.updateById(albumInfo);
        //更新track_info中的声音数量
        trackInfoMapper.updateOrderNum(trackInfo.getOrderNum(), albumInfo.getId());
        //删除云点播中的声音文件
        vodService.deleteMedia(trackInfo.getMediaFileId());

    }

    @Override
    public IPage<TrackListVo> getUserTrackPage(Page<TrackListVo> page, TrackInfoQuery trackInfoQuery) {
        //调用mapper方法
        return trackInfoMapper.selectUserTrackPage(page, trackInfoQuery);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveTrackInfo(TrackInfoVo trackInfoVo, Long userId) {
        //创建一个TrackInfo对象
        TrackInfo trackInfo = new TrackInfo();
        //给数据复制
        BeanUtils.copyProperties(trackInfoVo, trackInfo);
        //设置用户id
        trackInfo.setUserId(userId);
        //order_num 声音的序号
        //根据专辑id获取专辑对象
        AlbumInfo albumInfo = albumInfoMapper.selectById(trackInfo.getAlbumId());
        trackInfo.setOrderNum(albumInfo.getIncludeTrackCount() + 1);
        //	赋值流媒体相关字段数据 media_duration media_file_id media_size media_type; 可以调用云点播的api获取！
        TrackMediaInfoVo mediaInfo = vodService.getMediaInfo(trackInfoVo.getMediaFileId());
        trackInfo.setMediaDuration(mediaInfo.getDuration());
        trackInfo.setMediaUrl(mediaInfo.getMediaUrl());
        trackInfo.setMediaSize(mediaInfo.getSize());
        trackInfo.setMediaType(mediaInfo.getType());
        //保存声音
        trackInfoMapper.insert(trackInfo);

        //声音统计初始化
        this.saveTrackStat(trackInfo.getId(), SystemConstant.TRACK_STAT_PLAY);
        this.saveTrackStat(trackInfo.getId(), SystemConstant.TRACK_STAT_COLLECT);
        this.saveTrackStat(trackInfo.getId(), SystemConstant.TRACK_STAT_PRAISE);
        this.saveTrackStat(trackInfo.getId(), SystemConstant.TRACK_STAT_COMMENT);

        //更新专辑对应的声音总数
        albumInfo.setIncludeTrackCount(albumInfo.getIncludeTrackCount() + 1);
        this.albumInfoMapper.updateById(albumInfo);
    }

    public void saveTrackStat(Long trackId, String statPlay) {
        //创建声音统计对象
        TrackStat trackStat = new TrackStat();
        //赋值
        trackStat.setTrackId(trackId);
        trackStat.setStatType(statPlay);
        trackStat.setStatNum(new Random().nextInt(1000));
        this.trackStatMapper.insert(trackStat);
    }

    @Override
    public Map<String, Object> uploadTrack(MultipartFile file) {
        // 创建上传对象
        VodUploadClient client = new VodUploadClient(vodConstantProperties.getSecretId(), vodConstantProperties.getSecretKey());
        // 构建上传路径
        VodUploadRequest request = new VodUploadRequest();
        String tempPath = UploadFileUtil.uploadTempPath(vodConstantProperties.getTempPath(), file);
        request.setMediaFilePath(tempPath);
        // 执行上传并返回结果
        try {
            VodUploadResponse response = client.upload(vodConstantProperties.getRegion(), request);
            log.info("Upload FileId = {}", response.getFileId());
            //设置一个map，存储流媒体文件id以及url路径
            Map<String, Object> map = new HashMap<>();
            map.put("mediaFileId", response.getFileId());
            map.put("mediaUrl", response.getMediaUrl());
            //返回结果
            return map;
        } catch (Exception e) {
            // 业务方进行异常处理
            log.error("Upload Err", e);
        }
        //默认返回
        return new HashMap<>();
    }
}
